package com.gexada.simplechat.websocket;

import java.security.Principal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;

import org.springframework.context.ApplicationListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import com.gexada.simplechat.data.ActiveWebSocketUser;
import com.gexada.simplechat.data.ActiveWebSocketUserRepository;
import com.gexada.simplechat.data.ActiveWebSocketUserRole;
import com.gexada.simplechat.util.UserRoleHelper;

public class WebSocketConnectHandler implements ApplicationListener<SessionConnectEvent> {
	private ActiveWebSocketUserRepository repository;
	private SimpMessageSendingOperations messagingTemplate;

	public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate,
			ActiveWebSocketUserRepository repository) {
		super();
		this.messagingTemplate = messagingTemplate;
		this.repository = repository;
	}

	public void onApplicationEvent(SessionConnectEvent event) {
		MessageHeaders headers = event.getMessage().getHeaders();
		Principal authentication = SimpMessageHeaderAccessor.getUser(headers);
		if (authentication == null) {
			return;
		}
		boolean isService = false;

		if (authentication instanceof UsernamePasswordAuthenticationToken) {
			UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) authentication;
			Object principal = usernamePasswordAuthenticationToken.getPrincipal();
			if (principal instanceof UserDetails) {
				UserDetails userDetails = (UserDetails) principal;
				Collection<? extends GrantedAuthority> roles = userDetails.getAuthorities();
				isService = UserRoleHelper.isService(roles);
			}

		}
//		String dest = isService ? "/topic/organizations/signin" : "/topic/friends/signin";
		String id = SimpMessageHeaderAccessor.getSessionId(headers);
		repository.save(new ActiveWebSocketUser(id, authentication.getName(),
				isService ? ActiveWebSocketUserRole.SERVICE : ActiveWebSocketUserRole.CUSTOMER,
				Calendar.getInstance()));
		
		String dest =  "/topic/users/signin" ;
		messagingTemplate.convertAndSend(dest, Arrays.asList(authentication.getName()));
	}
}
